"""
支付相关API
"""
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse, RedirectResponse
from sqlalchemy.orm import Session
from typing import Dict, Any
from decimal import Decimal
import json

from database import get_db
from models.models import User
from models.order_models import Order
from routers.dependencies import get_current_user
from tools.comm import get_ali_object
from models.order_models import OrderItem
from models.goods_models import Goods
try:
    # 优先使用聊天模块中的工具进行推送
    from view.websocket import user_connections as ws_user_connections, send_json as ws_send_json
except Exception:
    ws_user_connections = {}
    async def ws_send_json(*args, **kwargs):
        return

router = APIRouter(prefix="/api/payment", tags=["支付"])

@router.post("/alipay/{order_no}")
async def alipay(
    order_no: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    发起支付宝支付
    """
    # 查询订单
    order = db.query(Order).filter(
        Order.order_no == order_no,
        Order.user_id == current_user.id
    ).first()

    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")

    if order.status != 0:
        raise HTTPException(status_code=400, detail="订单状态不正确")

    # 初始化支付宝支付对象
    pay = get_ali_object()

    # 生成支付的url
    query_params = pay.direct_pay(
        subject=f"小红书订单-{order_no}",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号
        total_amount=float(order.total_amount),  # 交易金额(单位: 元 保留俩位小数)
    )

    # 构建完整的支付URL（使用 AliPay 对象中的网关地址）
    pay_url = f"{pay.gateway}?{query_params}"

    # 调试信息，打印生成的URL
    print(f"支付宝支付URL: {pay_url}")
    print(f"使用的网关地址: {pay.gateway}")

    return JSONResponse({"code": 200, "url": pay_url, "order_no": order_no})

@router.get("/alipay/{order_no}")
async def alipay_get(
    order_no: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    发起支付宝支付 - GET方法
    """
    # 调用POST方法实现相同逻辑
    return await alipay(order_no, db, current_user)


@router.get("/callback")
@router.post("/callback")
async def alipay_callback(
    request: Request,
    db: Session = Depends(get_db)
):
    """
    支付宝回调处理
    """
    # 接收参数
    if request.method == "GET":
        data = dict(request.query_params)
    else:
        # 对于POST请求，我们需要处理表单数据
        data = dict(await request.form())

    # 复制数据并移除签名
    datames = {k: v for k, v in data.items()}

    # 删除字典中key为sign的记录
    sign = datames.pop('sign', None)
    if not sign:
        return 'fail'

    # 鉴权 订单号 流水号
    pay = get_ali_object()
    flag = pay.verify(datames, sign)

    if flag:
        # 支付宝流水号
        transaction_no = datames.get('trade_no', '')
        # 订单号
        order_no = datames.get('out_trade_no', '')

        try:
            # 更新订单状态
            order = db.query(Order).filter(Order.order_no == order_no).first()
            if order and order.status == 0:  # 只有未支付的订单才更新
                order.status = 1  # 已支付
                # 注意：如果需要保存支付宝交易号，需要在 Order 模型中添加 transaction_no 字段
                # order.transaction_no = transaction_no
                # 扣减库存（基于订单项）
                items = db.query(OrderItem).filter(OrderItem.order_id == order.id).all()
                for it in items:
                    goods = db.query(Goods).filter(Goods.id == it.goods_id).first()
                    if goods:
                        goods.stock = max(0, (goods.stock or 0) - int(it.qty))
                db.commit()

                # WebSocket 实时推送给用户（如果在线）
                try:
                    uid_key1 = f"user_{order.user_id}"
                    uid_key2 = str(order.user_id)
                    payload = {
                        "type": "payment_success",
                        "data": {
                            "order_no": order.order_no,
                            "status": "paid"
                        }
                    }
                    if uid_key1 in ws_user_connections:
                        await ws_send_json(ws_user_connections[uid_key1], payload)
                    elif uid_key2 in ws_user_connections:
                        await ws_send_json(ws_user_connections[uid_key2], payload)
                except Exception:
                    pass

            # 可以在这里添加其他业务逻辑，比如发送通知等

        except Exception as e:
            db.rollback()
            print(f"更新订单状态失败: {e}")
            return 'fail'
    else:
        print("鉴权失败")
        return 'fail'

    # 如果是GET请求，重定向到前端页面
    if request.method == "GET":
        # 重定向到订单页面
        return RedirectResponse(url="/orders")

    # POST请求返回success给支付宝
    return 'success'


@router.get("/query/{order_no}")
async def query_payment_status(
    order_no: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    查询支付状态
    """
    # 查询订单
    order = db.query(Order).filter(
        Order.order_no == order_no,
        Order.user_id == current_user.id
    ).first()

    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")

    # 初始化支付宝支付对象
    pay = get_ali_object()

    # 查询支付状态
    query_params = pay.query_pay(out_trade_no=order_no)

    # 这里应该调用支付宝的查询接口，实际项目中需要发送HTTP请求到支付宝
    # 为了简化，我们直接返回订单状态
    status_map = {
        0: "未支付",
        1: "已支付",
        2: "已取消"
    }

    return JSONResponse({
        "order_no": order_no,
        "status": order.status,
        "status_text": status_map.get(order.status, "未知状态")
    })